import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { GB } from '../../../environments/environment';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { I18nService } from '../../core/i18n/i18n.service';
import { ActionSheetConfig, SkinType, ActionSheetComponent, ActionSheetService, InfiniteLoaderComponent, ToptipsService } from 'ngx-weui';
import { NgForm, FormControl } from '@angular/forms';
import { ApiService } from 'src/app/core/api';
import { Global } from 'src/app/core/global';
import { Router } from '@angular/router';
import { StorageService } from 'src/app/core/sotrage/storage.service';

@Component({
	selector: 'app-index',
	templateUrl: './index.component.html',
	styleUrls: ['./index.component.less'],
})
export class LoginComponent implements OnInit {
	@ViewChild('languagebox', { static: true }) languagebox: ElementRef;
	pwError = false;
	jhNum;
	gb = GB;
	e: number; //換圖隨機數
	res: any = {
		id: '',
		vcode: '',
		password: '',
		worldpost: '1',
	};
	imageVerifyCodeId: any;
	imgUrl: any;
	lang: any = {};
	langShow = false;
	constructor(private i: I18nService, private api: ApiService, private global: Global, private router: Router, private sto: StorageService, private srv: ToptipsService, private translate: TranslateService) {
		this.lang = {lang: localStorage.getItem('lang') || 'zh'};
		this.translate.onLangChange.subscribe(params => {
			this.lang = params;
		});
	}
	onShow() {
		this.langShow = true;
	}
	onHide() {
		this.langShow = false;
	}
	changeLang(e) {
		this.i.changeLang(e);
		this.languagebox.nativeElement.blur();
	}
	ngOnInit() {
		this.api.post('生成图形验证码唯一id', {}).then(res => {
			this.imageVerifyCodeId = res['data']['imageVerifyCodeId'];
		});
	}
	onChangImgCode() {
		this.e = Math.random() * 10000;
	}
	onSave(f: NgForm) {
		let data = {
			// imageCode: f.value['imageCode'],
			// imageVerifyCodeId: this.imageVerifyCodeId,
			loginPw: f.value['loginPw'],
			level: 'normal',
		};
		f.value['id'].indexOf('@') == -1 ? (data['loginId'] = f.value['id']) : (data['email'] = f.value['id']);
		this.api
			.post('登录', data)
			.then(res => {
				this.sto.set('user', res['data']);
				if (sessionStorage.getItem('returnurl')) {
					const url = sessionStorage.getItem('returnurl');
					sessionStorage.removeItem('returnurl');
					this.router.navigateByUrl(url);
				} else {
					this.router.navigate(['/']);
				}
			})
			.catch(res => {
				if (res['data']['loginErrorNum'] < 3) {
					this.srv.warn(res['message']);
				} else {
					this.pwError = true;
					this.jhNum = 5 - res['data']['loginErrorNum'];
					if (this.jhNum == 0) {
						this.pwError = false;
					}
				}
			});
	}
}
